package tcp_proxy_middleware

import (
	"fmt"
	"gitee.com/zhoulvvv/my_go_gateway/dao"
	"gitee.com/zhoulvvv/my_go_gateway/public"
	"strings"
)

// TCP IP 黑名单中间件
func TCPBlackListModeMiddleware() func(c *TcpSliceRouterContext) {
	return func(c *TcpSliceRouterContext) {
		serviceInterface := c.Get("service")
		if serviceInterface == nil {
			c.Conn.Write([]byte("没有找到对应的服务信息"))
			c.Abort()
			return
		}
		service := serviceInterface.(*dao.ServiceDetail)
		// 获取IP白名单集合
		ipWhileList := []string{}
		if service.AccessControl.WhiteList != "" {
			ipWhileList = strings.Split(service.AccessControl.WhiteList, ",")
		}
		// 获取IP黑名单集合
		ipBlackList := []string{}
		if service.AccessControl.BlackList != "" {
			ipBlackList = strings.Split(service.AccessControl.BlackList, ",")
		}
		// ip:port c.Conn.RemoteAddr().String()
		splits := strings.Split(c.Conn.RemoteAddr().String(), ":")
		clientIP := ""
		if len(splits) == 2 {
			clientIP = splits[0]
		}
		// 判断是否开启权限校验
		if service.AccessControl.OpenAuth == 1 && len(ipWhileList) == 0 && len(ipBlackList) > 0 {
			if public.InStringsSlice(ipBlackList, clientIP) {
				c.Conn.Write([]byte(fmt.Sprintf("%s IP 没有权限访问", clientIP)))
				c.Abort()
				return
			}
		}
		c.Next()
	}
}
